<template>
	<view class="container">
		<view class="content">
			<!-- 地址信息 -->
<!--			<view class="address" @click="goAddress()"<-->
<!--				<view class="address-left">-->
<!--					<image src="/static/icon/address.png"></image>-->
<!--				</view>-->
<!--				<view class="address-right">-->
<!--					<view class="address-info">-->
<!--						<view class="address-info-top">-->
<!--							{{address.address}}-->
<!--						</view>-->
<!--						<view class="address-info-bottom">-->
<!--							<text class="address-name">{{address.nickname}}</text>-->
<!--							<text class="address-phone">{{address.phone}}</text>-->
<!--						</view>-->
<!--					</view>-->
<!--					<view class="address-righticon">-->
<!--						<image src="/static/icon/right.png"></image>-->
<!--					</view>-->
<!--				</view>-->
<!--			</view>-->
			<!-- 商品信息 -->
			<view class="goods">
				<view class="goods-info" v-for="(item,index) in goods" :key="item.id">
<!--					<view class="logistics">-->
<!--						<text class="logistics-left">生鲜快递发货</text>-->
<!--						<text class="logistics-right">上架24H发货，第三方物流配送</text>-->
<!--					</view>-->
					<view class="goods-item">
<!--						<view class="goods-left">-->
<!--							<image :src="item.post_url"></image>-->
<!--						</view>-->
						<view class="goods-center">
							<text class="goods-name">{{item.title}}</text>
							<text class="goods-num">数量：{{item.count}}</text>
						</view>
						<view class="goods-right">
							￥<text class="goods-price">{{item.price}}</text>
						</view>
					</view>
				</view>
			</view>
			<!-- 新增余额抵扣区域 -->
			<view class="balance-bar">
				<view class="balance-label">余额抵扣</view>
				<view class="balance-info">
					<text>可用余额：￥{{ userBalance }}</text>
					<switch :checked="useBalance" @change="onBalanceChange" color="#4e8ef7" :disabled="disableBalanceSwitch" />
				</view>
			</view>
			<view class="coupon" @click="chooseCoupon">
				<view class="coupon-left">
					优惠券
				</view>
				<view :class="[discountDetail ? 'active' : '', 'coupon-right']">
					<text >{{ discountDetail ? discountDetail : '请选择优惠券'}}</text>
					<image src="/static/icon/right.png"></image>
					<text v-if="selectedCoupon" class="coupon-cancel" @click.stop="cancelCoupon">取消</text>
				</view>
			</view>
      <!-- 金额明细区 -->
      <view class="amount-detail">
        <view class="amount-row">
          <text>商品总额</text>
          <text>￥{{ amount.amount }}</text>
        </view>
        <view class="amount-row" v-if="amount.coupon_deduct > 0">
          <text>优惠券抵扣</text>
          <text class="minus">-￥{{ amount.coupon_deduct }}</text>
        </view>
        <view class="amount-row" v-if="amount.balance_deduct > 0">
          <text>余额抵扣</text>
          <text class="minus">-￥{{ amount.balance_deduct }}</text>
        </view>
        <view class="amount-row total">
          <text>实付金额</text>
          <text class="total-pay">￥{{ amount.payment_amount }}</text>
        </view>
      </view>
		</view>
		<!-- 底部栏 -->
		<view class="bottombar">
			<view class="bottombar-content">
				<button class="primary-btn" @click="submit()">提交订单</button>
      		</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				address: {
				},
				goods: [],
        discount: 0,
        discountDetail: null,
        selectedCoupon: null,
        userBalance: 0,
        useBalance: false,
        disableBalanceSwitch: false,
        departure_date: null,
        type: 1
			}
		},
    computed: {
      goodsCount() {
        let count = 0
        this.goods.forEach(item => {
          count += item.count
        })
        return count
      },
      amount() {
        let amount = 0
        this.goods.forEach(item => {
          amount += item.count * item.price
        })
        // 先用优惠券抵扣
        let payment = amount - this.discount
        if (payment < 0) payment = 0
        // 只有优惠券抵扣后金额<=0时，余额抵扣不可用
        let disableBalance = payment <= 0
        // 再用余额抵扣
        let balanceDeduct = (!disableBalance && this.useBalance) ? Math.min(this.userBalance, payment) : 0
        let finalPay = payment - balanceDeduct
        if (finalPay < 0) finalPay = 0
        return {
          amount,
          payment_amount: Number(finalPay.toFixed(2)),
          balance_deduct: Number(balanceDeduct.toFixed(2)),
          coupon_deduct: Number(this.discount.toFixed(2)),
          disableBalance
        }
      },
    },
    watch: {
      // 监听优惠券和余额抵扣联动
      discount() {
        // 只有优惠券抵扣后金额<0时，自动关闭余额抵扣
        if ((this.amount.amount - this.discount) < 0 && this.useBalance) {
          this.useBalance = false
        }
        this.disableBalanceSwitch = this.amount.disableBalance
      },
      useBalance(val) {
        // 勾选余额抵扣时，自动清空优惠券（如需共享则注释掉）
        // if (val) {
        //   this.selectedCoupon = null
        //   this.discount = 0
        //   this.discountDetail = null
        //   uni.removeStorageSync('selectedCoupon')
        // }
      }
    },
    onShow() {
      if (!this.userInfo.id) {
        return
      }
      // 读取选中的优惠券
      const selectedCoupon = uni.getStorageSync('selectedCoupon')
      console.log('selectedCoupon',selectedCoupon)
      if (selectedCoupon && selectedCoupon.id) {
        // 选择优惠券时自动关闭余额抵扣
        // this.useBalance = false
        this.selectedCoupon = selectedCoupon
        this.discount = this.calcDiscount(selectedCoupon)
        this.discountDetail = this.getCouponDesc(selectedCoupon)
      } else {
        this.selectedCoupon = null
        this.discount = 0
        this.discountDetail = null
      }
      this.getUserBalance()
      // 联动禁用余额开关
      this.disableBalanceSwitch = this.amount.disableBalance
    },
    onLoad({ date, type }) {
      uni.removeStorageSync('selectedCoupon')
      this.goods = uni.getStorageSync('selectedTicketList')
      if (date) {
        this.departure_date = date || ''
      }
      if (type) {
        this.type = type || ''
      }
    },
		methods: {
      getUserBalance() {
        this.$store.dispatch('getUserInfo').then(res => {
          // 假设有API或store，实际可替换为真实接口
          if (res && res.balance !== undefined) {
            this.userBalance = res.balance
          } else {
            // 可用余额接口
            this.userBalance = 0
          }
        })
      },
      onBalanceChange(e) {
        // 余额抵扣被勾选时，自动清空优惠券
        this.useBalance = e.detail.value
      },
      chooseCoupon() {
        // 余额抵扣后剩余可支付金额<=0时，禁止选择优惠券
        let amountLeft = 0
        let total = 0
        this.goods.forEach(item => {
          total += item.count * item.price
        })
        if (this.useBalance) {
          // 先用余额抵扣
          let payment = total - this.discount
          if (payment < 0) payment = 0
          let balanceDeduct = Math.min(this.userBalance, payment)
          amountLeft = payment - balanceDeduct
        } else {
          amountLeft = total - this.discount
        }
        if (this.useBalance && amountLeft <= 0) {
          uni.showToast({
            icon: 'none',
            title: '当前余额已全部抵扣，无法再使用优惠券1'
          })
          return
        }
        console.log('amountLeft',amountLeft)
        // 只有余额抵扣后金额<=0时才自动关闭余额抵扣，否则允许共用
        // if (this.useBalance) this.useBalance = false
        uni.navigateTo({
          url: `/pages/coupon/coupon?source=payment&amount=${amountLeft.toFixed(2)}`
        })
      },
			// 跳转地址管理页面
			goAddress() {
				uni.navigateTo({
					url: "/pages/address/address"
				})
			},
			// 提交订单
			submit() {
        if (!this.userInfo.id) {
          uni.showModal({
            title: '提示',
            content: '请先登录',
            success: res => {
              if (res.confirm) {
                uni.navigateTo({
                  url: '/pages/login/index'
                });
              }
            }
          })
          return;
        }
        this.$api.createOrder({
          type: this.type,
          departure_date: this.departure_date,
          shop_user_id: this.goods[0].shop_user_id,
          address_id: this.address.id || 0,
          address_detail: this.address.address,
          address_phone: this.address.phone,
          address_nickname: this.address.nickname,
          user_id: this.userInfo.id,
          discount_amount: this.discount || 0,
          discount_coupon_id: this.selectedCoupon ? this.selectedCoupon.id : 0,
          delivery_fee_config_id: 0,
          delivery_amount: 0,
          amount: this.amount.amount,
          payment_amount: this.amount.payment_amount,
          balance_deduct: this.amount.balance_deduct,
          payment_type: 'wxin',
          order_delivery: 'self_pickup',
          count: this.goodsCount,
          goods: this.goods,
          name: this.goods[0].name,
          phone: this.goods[0].phone,
        }).then(res => {
          if (!res) {
            uni.showToast({
              icon: 'none',
              title: '下单失败',
            })
            return
          }
          if (res.status === 'pending_verification') {
            // 支付成功
            uni.showLoading({
              title: '支付成功',
            })
            setTimeout(() => {
              uni.redirectTo({
                url: "/pages/cart/paymentinfo?orderId=" + res.id
              })
            }, 1000);
          } else {
            this.getPay(res.id)
          }
        })
			},
      getPay(order_id){
        uni.showLoading({
          title:'微信支付请求'
        });
        const that = this
        this.$api.createPay({
          order_id
        }).then(payment =>{
          uni.requestPayment({
            provider: 'wxpay',
            timeStamp: payment.timestamp,
            nonceStr: payment.nonce_str,
            package: payment.package,
            signType: payment.signType,
            paySign: payment.paySign,
            success:(result)=> {
              uni.showToast({
                title:'支付成功'
              });
            },
            fail: (result) => {
              uni.showToast({
                icon:'none',
                title:'支付失败',
              });
            },
            complete: () => {
              setTimeout(() => {
                uni.redirectTo({
                  url: "/pages/cart/paymentinfo?orderId=" + order_id
                })
              }, 1000);
            }
          });
        }).catch(res=>{
          this.loading = false;
          setTimeout(() => {
            uni.redirectTo({
              url: "/pages/cart/paymentinfo?orderId=" + order_id
            })
          }, 1000);
        })
      },
      calcDiscount(coupon) {
        let total = 0
        this.goods.forEach(item => {
          total += item.count * item.price
        })
        if (!coupon || !coupon.coupon) return 0
        if (coupon.coupon.coupon_type === 1 || coupon.coupon.coupon_type === 3) {
          if (total >= (coupon.coupon.min_amount || 0)) {
            return Number(coupon.coupon.amount)
          }
        } else if (coupon.coupon.coupon_type === 2) {
          if (total >= (coupon.coupon.min_amount || 0)) {
            return Number((total * (1 - coupon.coupon.discount / 10)).toFixed(2))
          }
        }
        return 0
      },
      getCouponDesc(coupon) {
        if (!coupon || !coupon.coupon) return ''
        if (coupon.coupon.coupon_type === 1) {
          return `满${coupon.coupon.min_amount}减${coupon.coupon.amount}`
        }
        if (coupon.coupon.coupon_type === 2) {
          return `${coupon.coupon.discount}折`
        }
        if (coupon.coupon.coupon_type === 3) {
          return `无门槛减${coupon.coupon.amount}`
        }
        return ''
      },
      cancelCoupon() {
        this.selectedCoupon = null
        this.discount = 0
        this.discountDetail = null
        uni.removeStorageSync('selectedCoupon')
      }
		}
	}
</script>

<style>
	page {
    height: 100%;
    overflow: hidden;
		background: #F8F9FA;
	}
</style>

<style lang="scss">
  .container {
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
	.primary-btn {
		width: 90%;
		height: 80rpx;
		line-height: 80rpx;
	}
  }
	.content {
    flex-grow: 1;
		margin: 20rpx 30rpx;
    overflow: auto;
	}
	.address {
		display: flex;
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 32rpx 20rpx;

		.address-left {

			image {
				width: 48rpx;
				height: 48rpx;
			}
		}

		.address-right {
      flex-grow: 1;
			display: flex;
			align-items: center;

			.address-info {
        flex-grow: 1;
				display: flex;
				flex-direction: column;
				padding: 0rpx 40rpx 0rpx 20rpx;

				.address-info-top {
					font-size: 30rpx;
					font-weight: 600;
					color: #333333;
				}

				.address-info-bottom {
					font-size: 24rpx;
					color: #999999;
					margin-top: 6rpx;

					.address-phone {
						margin-left: 16rpx;
					}
				}
			}

			.address-righticon {

				image {
					width: 48rpx;
					height: 48rpx;
				}
			}
		}
	}

	.goods {
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-top: 22rpx;
		display: flex;
		flex-direction: column;
		gap: 44rpx;

		.logistics {
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 24rpx;
			padding-bottom: 30rpx;

			.logistics-left {
				font-weight: 600;
			}

			.logistics-right {
				color: #f56c6c;
			}
		}

		.goods-item {
			display: flex;
			padding: 10rpx 0rpx;

			.goods-left {

				image {
					width: 130rpx;
					height: 130rpx;
				}
			}

			.goods-center {
        flex-grow: 1;
				display: flex;
				flex-direction: column;
				padding: 0rpx 60rpx 0rpx 0;

				.goods-name {
					font-size: 26rpx;
					font-weight: 600;
					color: #333333;
				}

				.goods-spec {
					font-size: 24rpx;
					color: #999999;
					margin-top: 10rpx;
				}

				.goods-num {
					font-size: 24rpx;
					color: #999999;
				}
			}

			.goods-right {
				font-size: 22rpx;
				font-weight: 600;
        color: #f56c6c;
				.goods-price {
					font-size: 32rpx;
          color: #f56c6c;
				}
			}

		}
	}

	.coupon {
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-top: 22rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.coupon-left {
			font-size: 30rpx;
		}

		.coupon-right {
			display: flex;
			align-items: center;
      color: #999393;
      &.active {
        color: #F55726;
      }
			text {
				font-size: 28rpx;
			}

			image {
				width: 48rpx;
				height: 48rpx;
			}
		}
	}

	.bottombar {
    flex-shrink: 0;
		width: 100%;
		background: #FFFFFF;
		display: flex;
		flex-direction: row;
		justify-content: flex-end;

    padding-bottom: 50rpx;
		.bottombar-content {
      width: 100%;
      display: flex;
      align-items: center;
			padding: 16rpx 30rpx 20rpx 32rpx;

			text {
				color: #333333;
				font-size: 24rpx;
			}

			.bottombar-label {
				font-size: 22rpx;
				color: #F55726;
			}

			.bottombar-price {
				font-size: 32rpx;
				font-weight: 600;
				color: #F55726;
				margin-right: 28rpx;
			}

		}

		button {
			border-radius: 36rpx;
			background: #4e8ef7;
			color: #FFFFFF;
			font-size: 24rpx;
		}
	}

	.balance-bar {
		background: #fff;
		border-radius: 20rpx;
		margin: 22rpx 0 0 0;
		padding: 30rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.03);
	}
	.balance-label {
		font-size: 30rpx;
		color: #333;
		font-weight: 600;
	}
	.balance-info {
		display: flex;
		align-items: center;
		gap: 24rpx;
		font-size: 26rpx;
		color: #888;
	}
  .coupon-cancel {
    color: #f44336;
    font-size: 24rpx;
    margin-left: 16rpx;
    border: 1rpx solid #f44336;
    border-radius: 8rpx;
    padding: 2rpx 12rpx;
    background: #fff;
  }
  .amount-detail {
    background: #fff;
    border-radius: 20rpx;
    margin: 22rpx 0 0 0;
    padding: 30rpx;
    box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.03);
    font-size: 26rpx;
  }
  .amount-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12rpx;
    color: #333;
  }
  .amount-row.total {
    font-size: 30rpx;
    font-weight: bold;
    color: #F55726;
    margin-top: 18rpx;
    margin-bottom: 0;
  }
  .amount-row .minus {
    color: #4e8ef7;
  }
  .amount-row .total-pay {
    color: #F55726;
    font-size: 34rpx;
    font-weight: bold;
  }
  .amount-row.summary-row {
    font-size: 28rpx;
    color: #333;
    margin-top: 18rpx;
    margin-bottom: 0;
    font-weight: 500;
  }
  .summary-pay {
    color: #F55726;
    font-size: 30rpx;
    font-weight: bold;
  }
  .bottombar-content {
    width: 100%;
    display: flex;
    align-items: center;
    padding: 16rpx 30rpx 20rpx 32rpx;
    justify-content: center;
  }
  .submit-btn {
    width: 100%;
    height: 88rpx;
    border-radius: 44rpx;
    background: #4e8ef7;
    color: #fff;
    font-size: 30rpx;
    font-weight: bold;
    margin: 0;
    box-shadow: 0 4rpx 16rpx rgba(78,142,247,0.08);
  }
</style>
